
function Promise(executor){
    this.PromiseState = 'pending';
    this.PromiseResult = undefined;
    this.callbacks = [];
    let resolve = (value)=>{
        if(this.PromiseState !== 'pending') return;
        this.PromiseState = 'fulfilled';
        this.PromiseResult = value;
        if(this.callbacks.length){
            this.callbacks.forEach(item=>{
                item.success();
            })
        }
    }
    let reject = (reason)=>{
        if(this.PromiseState !== 'pending') return;
        this.PromiseState = 'rejected';
        this.PromiseResult = reason;
        if(this.callbacks.length){
            this.callbacks.forEach(item=>{
                item.fail();
            })
        }
    }
    try{
        executor(resolve,reject);
    }catch(e){
        reject(e);
    }
}
Promise.prototype.then = function(onResolved, onRejected){
    console.log(this.PromiseState);
    if(this.PromiseState === 'fulfilled'){
        let p1 = new Promise((resolve,reject)=>{
            let rs = onResolved(this.PromiseResult);
            if(rs instanceof Promise){
                // 是 Promise
                // rs 
                // rs.PromiseState === 'fulfilled'
                // rs.PromiseState ===  'rejected'
                // rs是promise对象，那就可以调用 then方法
                rs.then(v=>{
                    resolve(v)
                },r=>{
                    reject(r);
                });
            }else{
                // 不是promise
                resolve(rs);
            }
        })
        return p1;
    }
    if(this.PromiseState === 'rejected'){
        onRejected(this.PromiseResult)
    }
    if(this.PromiseState === 'pending'){
        this.callbacks.push({
            success:()=>{
                onResolved(this.PromiseResult);
            },
            fail:()=>{
                onRejected(this.PromiseResult);
            }
        })
    }
}